<?php

/**
 * 管理员模型
 * 
 * @author 陈蕾
 */

class Model_Admin extends ORM
{
    // Model table information
    protected $_table_name = 'admin';
    protected $_ignored_columns = array('password_confirm');

	// Table primary key and value
	protected $_primary_key  = 'id';
	protected $_primary_val  = 'name';

    // Validation members
    protected $_filters = array(
    	'name' => array(
    		'htmlspecialchars' => NULL
    	)
    );
    protected $_rules = array(
        'name'=> array(
            'not_empty' => NULL,
            'min_length' => array('5'),
            'max_length' => array('20')
        ),
        'password' => array(
            'not_empty' => NULL,
            'min_length' => array('8'),
            'max_length' => array('16')
        )
    );

    /**
     * 验证登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return mixed 成功返回数据集, 错误返回false
     */
    public function verify_login($username, $password)
    {
        $ret = $this->where('name', '=', $username)
            ->and_where('password', '=', md5($password))
            ->find();

        if ($this->loaded()) {
            // 登录成功, 将当前时间保存为最后登录时间
            $this->last_login = date('Y-m-d H:i:s');
            $this->save();
            return $this->as_array();
        }

        return FALSE;
    }

    /**
     * 检查用户名是否可用
     * @param Validate $array 验证对象
     * @param string $field 字段名
     */
    public static function username_available(Validate $array, $field)
    {
        if (self::username_exists($array[$field])) {
            $array->error($field, 'username_available', array($array[$field]));
        }
    }

    /**
     * 检查用户名是否存在
     * @param string $value 用户名
     * @return boolean
     */
    public static function username_exists($value)
    {
        return (bool) DB::select(array('COUNT("*")', 'total_count'))
            ->from('admin')
            ->where('name', '=', $value)
            ->execute()
            ->get('total_count');
    }

    /**
     * 保存
     */
    public function save()
    {
        if (array_key_exists('password', $this->_changed)) {
            $this->_object['password'] = md5($this->_object['password']);
        }

        return parent::save();
    }
}